import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import { Draw, Modify, Snap } from 'ol/interaction';
import { OSM, Vector as VectorSource } from 'ol/source';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';

var raster = new TileLayer({
    source: new OSM()
});

//数据源
var source = new VectorSource();
//要素图层
var vector = new VectorLayer({
    source: source,
    style: new Style({
        //填充
        fill: new Fill({
            color: 'rgba(255, 255, 255, 0.2)'
        }),
        //笔画
        stroke: new Stroke({
            color: '#ffcc33',
            width: 2
        }),
        image: new CircleStyle({
            radius: 7,
            fill: new Fill({
                color: '#ffcc33'
            })
        })
    })
});

var map = new Map({
    layers: [raster, vector],
    target: 'map',
    view: new View({
        center: [-11000000, 4600000],
        zoom: 4
    })
});
//修改
var modify = new Modify({
    source: source
});
//添加到 map
map.addInteraction(modify);

// 绘制及捕捉
var draw, snap;
var typeSelect = document.getElementById('type');
// 根据选择的要素类型添加相应交互操作
// type的值为 GeometryType: 'Point', 'LineString', 'LinearRing', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection', 'Circle'
// 绘制规则多边形需使用 geometryFunction 属性
function addInteractions() {
    draw = new Draw({
        source: source,
        // 如果为 None，则为默认的拖拽地图
        type: typeSelect.value
    });
    // 初始化
    map.addInteraction(draw);
    snap = new Snap({ source: source });
    map.addInteraction(snap);
}

//选项变化时重新添加交互操作
typeSelect.onchange = function() {
    map.removeInteraction(draw);
    map.removeInteraction(snap);
    addInteractions();
};

addInteractions();